package com.springboot_shopping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot_shopping.Mapper.ProductMapper;
import com.springboot_shopping.vo.IndexProductVo;
import com.springboot_shopping.entity.Product;
import com.springboot_shopping.vo.ProductDetailVo;
import com.springboot_shopping.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;


    @Override
    public List<Product> findAll() {
        return productMapper.selectList(null);
    }

    //分页
//    @Override
//    public PageInfo<Product> getPage(Product product, Integer pageNum) {
//        PageHelper.startPage(pageNum,6,"id desc");
//        List<Product> list = productMapper.selectList(null);
//        return new PageInfo<>(list);
//    }

//    @Override
//    public IPage<Product> findByPage(IPage<Product> page) {
//        return productMapper.selectPage(page, null);
//    }

    // 分页
    @Override
    public IPage<Product> getPage(Product product, Integer pageNum) {
      //创建分页对象，每页6条
        Page<Product> page = new Page<>(pageNum, 6);

        // 创建查询条件
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();

        // 添加动态查询条件（可选）
        if (product != null) {
            if (StringUtils.hasText(product.getTitle())) {
                queryWrapper.like("product_name", product.getTitle());
            }
            if (product.getPrice() != null) {
                queryWrapper.le("price", product.getPrice()); // 价格小于等于
            }
            if (product.getStock() != null) {
                queryWrapper.eq("category", product.getStock());
            }
        }

        // 执行分页查询
        return productMapper.selectPage(page, queryWrapper);
    }

    // 查询商品详情
    @Override
    public ProductDetailVo getProductDetail(Integer id) {
        return productMapper.findDetailById(id);
    }


    //首页商品展示
    @Override
    public List<IndexProductVo> getProductsForIndex() {
        return productMapper.findProductsForIndex();
    }
}
